<template>
  <view class="" v-for="team in props.teamList" :key="team.id">
    <up-card
      padding="0rpx"
      :foot-border-top="false"
      :head-border-bottom="false"
      style="background-color: #f6f8fa"
    >
      <template #body>
        <view class="" slot="body">
          <view
            class="u-body-item u-flex u-col-between u-p-t-0"
            style="position: relative"
          >
            <image
              :src="imgs"
              mode="aspectFill"
              style="width: 300rpx; height: 300rpx"
            ></image>
            <view class="team-info">
              <view class="team-name">{{ team.teamName }}</view>
              <view class="team-description">{{ team.description }}</view>
              <up-tag
                plain
                size="mini"
                type="warning"
                style="margin: 8rpx; margin-left: 0rpx"
              >
                {{ teamStatusEnum[team.teamState] }}
              </up-tag>
              <view class="team-member-count">{{
                `队伍人数: ${team.hasJoinNum}/${team.maxNum}`
              }}</view>
              <view v-if="team.expireTime" class="team-expire-time">{{
                '过期时间: ' + formatDate(team.expireTime)
              }}</view>
              <view class="team-create-time">{{
                '创建时间: ' + formatDate(team.createTime)
              }}</view>
            </view>
          </view>
        </view>
      </template>
      <template #foot>
        <view
          style="
            display: flex;
            justify-content: flex-end;
            align-items: center;
            width: 50%;
            margin-left: auto;
          "
        >
          <up-button @click="getInfoTeam(team.id)">查看</up-button>
          <up-button
            type="primary"
            @click="preJoinTeam(team)"
            v-if="team.userId !== currentUser?.id && !team.hasJoin"
            >加入队伍</up-button
          >
          <up-button
            @click="doUpdateTeam(team.id)"
            v-if="team.userId === currentUser?.id"
            >更新</up-button
          >
          <up-button @click="doQuitTeam(team.id)" v-if="team.hasJoin"
            >退出</up-button
          >
          <up-button
            @click="doDeleteTeam(team.id)"
            v-if="team.userId === currentUser?.id"
            >解散</up-button
          >
        </view>
      </template>
    </up-card>
  </view>
  <up-modal
    :show="showPasswordDialog"
    :title="'输入密码'"
    @confirm="doJoinTeam"
    showCancelButton
    @cancel="doJoinCancel"
  >
    <up-input
      placeholder="请输入密码"
      border="surround"
      v-model="teamPassword"
    ></up-input>
  </up-modal>
</template>

<script setup lang="ts">
import type { teamType } from '@/models/team'
import { teamStatusEnum } from '@/constants/team'
import imgs from '@/static/vue.svg'
import myAxios from '@/plugins/myAxios'
import { getCurrentUser } from '@/services/user'
import type { userType } from '@/models/user'
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

interface TeamCardListProps {
  teamList: teamType[]
}
// 在子组件中定义 emit 事件
const emit = defineEmits(['updateTeamList'])
const props = withDefaults(defineProps<TeamCardListProps>(), {
  //@ts-ignore
  teamList: [] as teamType[]
})

const currentUser = ref('')
const showPasswordDialog = ref(false)
const teamPassword = ref('')
const joinTeamId = ref(0)
const loading = ref(false)

/**
 * Format date to yyyy-MM-dd
 * @param dateString - The date string to format
 * @returns Formatted date string
 */
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // Months are zero-based
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

/**
 * 加载用户信息
 */
onLoad(async () => {
  currentUser.value = await getCurrentUser()
})

const preJoinTeam = (team: teamType) => {
  joinTeamId.value = team.id
  if (team.teamState === 0) {
    doJoinTeam()
  } else {
    showPasswordDialog.value = true
  }
}

/**
 * 查看队伍信息详情
 */
const getInfoTeam = (id: number) => {
  uni.navigateTo({
    url: `/pages/team/info?id=${id}`
  })
}

/**
 * 加入队伍
 * @param id
 */
const doJoinTeam = async () => {
  if (!joinTeamId.value) {
    return
  }
  try {
    const res = await myAxios.post('/team/join', {
      teamId: joinTeamId.value,
      teamPassword: teamPassword.value
    })
    if (res?.code === 0 && res) {
      uni.showToast({
        title: '加入成功',
        icon: 'success'
      })
      doJoinCancel()
    } else {
      uni.showToast({
        title: '加入失败' + (res.description ? `,${res.description}` : ''),
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '加入失败',
      icon: 'none'
    })
  }
}

/**
 * 退出队伍
 * @param id
 */
const doQuitTeam = async (id: number) => {
  try {
    const res = await myAxios.post('/team/quit', {
      teamId: id
    })
    if (res?.code === 0 && res) {
      uni.showToast({
        title: '退出队伍成功',
        icon: 'success'
      })
      // 退出成功后触发父组件的 onTabChange
      emit('updateTeamList')
    } else {
      uni.showToast({
        title: '退出失败' + (res.description ? `,${res.description}` : ''),
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '退出失败',
      icon: 'none'
    })
  }
}

/**
 * 解散队伍
 * @param id
 */
const doDeleteTeam = async (id: number) => {
  try {
    const res = await myAxios.post('/team/delete', {
      id
    })
    if (res?.code === 0 && res) {
      uni.showToast({
        title: '解散队伍成功',
        icon: 'success'
      })
      // 解散成功后触发父组件的 onTabChange
      emit('updateTeamList')
    } else {
      uni.showToast({
        title: '解散队伍失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '解散队伍失败',
      icon: 'none'
    })
  }
}

/**
 * 更新队伍信息
 * @param id
 */
const doUpdateTeam = (id: number) => {
  uni.navigateTo({
    url: `/pages/team/update?id=${id}`
  })
}

const doJoinCancel = () => {
  teamPassword.value = ''
  joinTeamId.value = 0
  showPasswordDialog.value = false
}
</script>

<style scoped>
.team-info {
  margin-left: 15px; /* Add margin for better spacing */
}

.team-name {
  font-weight: bold;
  font-size: 18px;
  color: #333;
  margin-top: 5px;
}

.team-description {
  color: #666;
  margin-top: 3px;
  font-size: 14px;
}

.team-member-count,
.team-expire-time,
.team-create-time {
  color: #999; /* Lighter color for less emphasis */
  font-size: 12px; /* Smaller font size for secondary information */
  margin-top: 2px; /* Add some spacing */
}
</style>
